import React, { useRef, useEffect, useState, useCallback } from 'react';
import { TextEditor } from 'text-editor';
import { editorManager, debounce } from '../../utils';
import useProjectStore from '../../stores/projectStore';
import styles from './Editor.module.css';

const Editor = ({ 
  onEditorReady,
  isDarkTheme = false
}) => {
  const editorContainerRef = useRef(null);
  const [isEditorReady, setIsEditorReady] = useState(false);
  const textEditorRef = useRef(null);
  const { updateCurrentFileContent } = useProjectStore();

  // 编辑器内容变化处理函数 - 使用防抖机制
  const handleEditorChange = useCallback(
    debounce(async (content) => {
      try {
        // 自动保存到文件系统
        await updateCurrentFileContent(content);
      } catch (error) {
        console.error('自动保存失败:', error);
      }
    }, 1000), // 1秒防抖
    [updateCurrentFileContent]
  );

  const initializeEditor = async () => {
    // 防止重复初始化
    if (textEditorRef.current) {
      return;
    }

    try {
      const textEditor = new TextEditor();
      textEditorRef.current = textEditor;
      
      // 先渲染编辑器，确保内部 editor 实例已创建
      // 传入内容变化监听器
      textEditor.render(editorContainerRef.current, {
        updateListener: handleEditorChange
      });
      
      // 设置主题和语言
      const themeName = isDarkTheme ? 'dark' : 'light';
      textEditor.setTheme(themeName);
      textEditor.setLanguage('python');
      
      // 渲染完成后再设置到 editorManager
      editorManager.setEditor(textEditor);
      setIsEditorReady(true);
      
      if (onEditorReady) {
        onEditorReady(textEditor);
      }
    } catch (error) {
      console.error('Error initializing editor:', error);
    }
  };

  useEffect(() => {
    if (!editorContainerRef.current) {
      return;
    }

    initializeEditor();
  }, []);

  // 监听主题变化
  useEffect(() => {
    if (textEditorRef.current && isEditorReady) {
      const themeName = isDarkTheme ? 'dark' : 'light';
      textEditorRef.current.setTheme(themeName);
    }
  }, [isDarkTheme, isEditorReady]);

  return (
    <div className={styles.editor} ref={editorContainerRef}>
      {!isEditorReady && (
        <div className={styles.loadingContainer}>
          <div className={styles.loadingContent}>
            <div className={styles.loadingMessage}>正在加载编辑器...</div>
            <div className={styles.loadingSubtext}>
              如果长时间未加载，请检查控制台错误信息
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Editor;
